$(function(){
	loadDictionaryDataSettings();
})
/**
 * 加载表格
 */
function loadDictionaryDataSettings(){
	$.post(contextPath + "/dictionary/getDictionaryList.dhc").done(function(data){
		var columns=[{      "title":'',
							"data": '',			// 表数据的数据属性或操作方法
							"className": 'details-control',  // 指定单元格样式
							"render": function(obj, type, full){    // Render (process) the data for use in the table
							}
						},{
							"title":"字典代码",
							"data": "dicCode"
						},{
							"title":"字典描述",
							"data": "dicDesc"
						},{
							"title":"操作",
							"data": "operation",
							"render": function(obj, type, full){    // Render (process) the data for use in the table
								return "<button class=\"btn\" style=\"padding:4px 10px;\" onclick=\"mergeDictionary('"+full.dicCode+"')\"><i class=\"fa fa-pencil\"></i></button>  <button class=\"btn\" style=\"padding:4px 10px;\" onclick=\"delDictionaryData('"+full.dicCode+"')\"><i class=\"fa fa-times fa fa-white\"></i></button>";						
							}
						}];
		var paramsDataTables={info:false,rownumbers:true,order:[[1,'asc']]};
		var columnDefs=[
        	 {   targets: [ '_all' ] }];
    		var createdRow=function( row, data, dataIndex ) {
        	    $(row).attr("dicid",data.id);
           	}
    		var initComplete= function(settings, json) {
    		 var dicDataBtn = $('<span style="float:right">&nbsp;&nbsp;<button id="saveDictionaryBtn" class="btn btn-primary">新 增 <i class=\"fa fa-plus\"></i></button></span>') ;
         	$("#dictionary_setting_filter").before(dicDataBtn);
     	dicDataBtn.click(function(){
     		addDictionary() ;
     	});
	  }
	  paramsDataTables.columnDefs=columnDefs;
	  paramsDataTables.createdRow=createdRow;
	  paramsDataTables.initComplete=initComplete
	  var oaTable ;
	  if(oaTable!=null) oaTable.destroy();
	   oaTable = $("#"+tabId+" #dictionary_setting").dataTableBasic(columns,data.data,paramsDataTables);
	  $("#"+tabId+" #dictionary_setting>tbody").off("click", "td.details-control");
		$("#"+tabId+" #dictionary_setting>tbody").on('click', 'td.details-control', function () {
			var nTr = $(this).closest('tr');
			var row = oaTable.row( nTr );
			if (row.child.isShown()){
				row.child.hide();
				nTr.removeClass("shown");
			} else {
				nTr.addClass("shown");
				row.child("正在加载...").show();
				try{
						$.post(contextPath + "/dictionaryData/getDictionaryDataByCode.dhc", {dicCode: row.data().dicCode}).done(function(data){
							var str = '';
							str+='<div style="width:80%;margin:0 10% 0 10% ;">';
							str+=' <table class="table table-striped table-bordered" style="width:100%;"> </table> ';
							str+='<center> <button id="saveDictionaryDataBtn">保存</button></center>';
							if(row.data().dicCode == "MANAGE_TARGET"){
								str+='<p>注：绩效字典值保存格式:以“manage_”开头</p>';
							}
							else if(row.data().dicCode == "STD_TARGET"){
								str+='<p>注：标杆字典值保存格式:以“std_”开头,其中“外院标杆”以“std_out_”开头</p>';
							}
							str+='</div>';
						    var columns=[{
											"title":'',
											"data": 'addReleaseQuota',
											"className": 'add_release'
										},{
											"title":'编码',
											"data": "DICCODE"
										},{
											"title":'字典值',
											"data": "DICVALUE"
										},{
											"title":'描述',
											"data": "DICDESC"
										},{
											"title":'备注',
											"data": "DICRESUME"
										},{
											"data": 'delReleaseQuota',
											"className": 'del_release'
										}];
							var columnDefs=[{
											targets: [ '_all' ],    // 适用于指定一个特定的列
						               	 	createdCell: function (td, cellData, rowData, row, col) {
											     // 初始化表格时添加数据
					                    		 $(td).text(""); // 去除表格中的文字
					                    		 if(col == 0  || col == 5){ // 第一列和最后一列不处理
					                    			 return ;
					                    		 }
					                    		 var nNewInput = document.createElement("input");
					                    		 $(nNewInput).attr("value",cellData);
					                    		 td.appendChild(nNewInput);
					                    		 if(col == 1 || col == 2){
					                    		 $(nNewInput).attr("disabled","disabled");
					                    		 }
					                    		 $(nNewInput).css({"text-align":"left", "vertical-align":"center"});
											    }
							               	 }];
							var createdRow=function( row, data, dataIndex ) {
					    	    $(row).attr("dicid",data.id);
							};
						  var paramsDataTables={paging:false,lengthChange:false,tableTitle:row.data().dicDesc+'-字典值',searching:false,ordering:false,info:false,rownumbers:true,order:[[1,'asc']]};
						  paramsDataTables.columnDefs=columnDefs;
						  paramsDataTables.createdRow=createdRow;
						  row.child(str).show();
						  var oaTablec = $(nTr).next().find("td>div>table").dataTableBasic(columns,data.data,paramsDataTables);
						
						if(data.data.length==0){
								$(nTr).next().find("td>div table>tbody>tr").remove();
								var nNewRow = addTr();
								$(nTr).next().find("td>div table>tbody").append(nNewRow);
								}
							var quotaReleaseList = [];
							
							
							$(nTr).next().find("td>div table>tbody").off("click", "td.add_release");
							
							$(nTr).next().find("td>div table>tbody").on('click', 'td.add_release', function () {
								var nTr1 = $(this).parents('tr')[0];
								var nNewRow = addTr();
								$(nTr1).after(nNewRow);
								// 增加行后 在输入处获取焦点
								$(this).parents("tr").next().find("input").eq(1).focus();
							});
							
							function addTr(){
								var nNewRow = document.createElement("tr");
								var nNewCell1 = document.createElement("td");
								nNewCell1.setAttribute("class", "add_release sorting_1");
								nNewRow.appendChild( nNewCell1 );
								var nNewCell2 = document.createElement("td");
								var nNewInput2 = document.createElement("input");
								$(nNewInput2).attr("value",$(nTr).children("td").eq(1).text());
								$(nNewInput2).attr("disabled","disabled");
								nNewCell2.appendChild(nNewInput2);
								nNewRow.appendChild( nNewCell2 );
								
								var nNewCell3 = document.createElement("td");
								var nNewInput3 = document.createElement("input");
								nNewCell3.appendChild(nNewInput3);
								nNewRow.appendChild( nNewCell3 );
								
								var nNewCell4 = document.createElement("td");
								var nNewInput4 = document.createElement("input");
								nNewCell4.appendChild(nNewInput4);
								nNewRow.appendChild( nNewCell4 );
								
								var nNewCell5 = document.createElement("td");
								var nNewInput5 = document.createElement("input");
								nNewCell5.appendChild(nNewInput5);
								nNewRow.appendChild( nNewCell5 );
								
								var nNewCell6 = document.createElement("td");
								nNewCell6.setAttribute("class", "del_release sorting_1");
								nNewRow.appendChild( nNewCell6 );
								return nNewRow;
							}
							
							$(nTr).next().find("td>div table>tbody").off("click", "td.del_release");
							$(nTr).next().find("td>div table>tbody").on('click', 'td.del_release', function () {
								var nTr1 = $(this).parents('tr')[0];
								$(nTr1).remove();
							});
							
							$(nTr).next().find("td").find("#saveDictionaryDataBtn").click(function(){
								
								var dicCodeD = $(nTr).find("td:eq(1)").html();   
								var dictionaryDatas = [];
								for(var o=0; o<$(nTr).next().find("td>div table>tbody").find("tr").size(); o++){
									var tr = $(nTr).next().find("td>div table>tbody").find("tr").eq(o);
									var dicValueD = $(tr).find("td:eq(2)").html();
									if($(tr).find("td:eq(2)>input").size()>0){
										dicValueD = $(tr).find("td:eq(2) input").val();
									}
									var dicDescD = $(tr).find("td:eq(3)").html();
									if($(tr).find("td:eq(2)>input").size()>0){
										dicDescD = $(tr).find("td:eq(3)>input").val();
									}
									var dicResumeD = $(tr).find("td:eq(4)").html();
									if($(tr).find("td:eq(2)>input").size()>0){
										dicResumeD = $(tr).find("td:eq(4)>input").val();
									}
									
									var dictionaryData = {"dicCode": dicCodeD, "dicValue": dicValueD, "dicDesc": dicDescD,"dicResume": dicResumeD, "dictionaryDataIndex": o}
									if(dictionaryData.dicCode){
										dictionaryDatas.push(dictionaryData);
									}
								}
								//清除无效的关联指标
								var invalidDictionaryDatas = " ";
								var  arry = new Array();
								for(var o in dictionaryDatas){
									var dictionaryData = dictionaryDatas[o];
									
									if(!dictionaryData.dicValue){ // 判断数据是否为空
										var errorLog = " 字典值不允许为空 ，请输入" ;
										drgUI.error(errorLog) ;
										// 遍历每行的第二个数据，如果为空则获取焦点
										$(nTr).next().find("td table tbody tr").each(function(){
											var val = $(this).find(":input").eq(1).val() ;
											if(!val){
												$(this).find(":input").eq(1).focus() ;
											}
											return ; // 发现之后不再往下遍历
										});
										$(nTr).next().find("td.details").find("#saveDictionaryDataBtn").removeAttr("disabled");
										return ;
									}
									invalidDictionaryDatas += "'"+dictionaryData.dicValue+"',"
								}
								//数据压入数组
								for(i=0;i<dictionaryDatas.length;i++){
									arry.push(dictionaryDatas[i].dicValue)
								}
								//用字符串查找判断新数组是否有重复数据
								 var arryNew=new Array;
								 for(var i = 0; i < arry.length; i++)
								 {
								 	arryNew.push($.inArray(arry[i], arry))
								 	}
								 	var nary=arryNew.sort();
									for (var i = 0; i < arryNew.length; i++) {

									if (nary[i] == nary[i+ 1]) {
									drgUI.error("字典值不允许重复，请重新输入!") ;
								return;
										}
									}
								invalidDictionaryDatas = invalidDictionaryDatas.substring(0, invalidDictionaryDatas.length-1);
								// 把不在 invalidDictionaryDatas 中的指标先删除
								$.post(contextPath + "/dictionaryData/delInvalidDictionaryDatas.dhc", {param: invalidDictionaryDatas, dicCode: dicCodeD}).done(function(data){
									if(!data.success){
										var errorLog = "保存失败,日志："+data.errorMessage;
										drgUI.error(errorLog) ;
									}else{
										var ajaxCount = dictionaryDatas.length;
										var ajaxS = 0;
										var errorLog;  // 报错后返回
										for(var o in dictionaryDatas){
											var dictionaryData = dictionaryDatas[o];
											// 指标逐条保存
											$.post(contextPath + "/dictionaryData/saveDictionaryData.dhc", {param : JSON.stringify(dictionaryData)}).done(function(){
												ajaxS ++;
												if(!data.success){
													errorLog += "指标("+node.code+")报错\n"+data.errorMessage;
													errorLog += "\n";
												}
											});
										}
										var timer = setInterval(function(){
											if(ajaxS == ajaxCount){
												clearInterval(timer);
												if(errorLog){
													drgUI.error(errorLog) ;
												}else{
													drgUI.success("保存成功") ;
												}
												/**
												 * 在保存数据的过程中save按钮是失效的。
												 */
												$(nTr).next().find("td").find("#saveDictionaryDataBtn").removeAttr("disabled");
											}
										}, 500);
									}
								});
								
							})
						});
				}catch(e){
					row.child("出错了...").show();
				}
			}
	    });
	})
}
/**
 * 添加字典
 */
function addDictionary(){
	$.post(contextPath+"/pages/common/top-dialog-buttons.jsp").done(function(data){
		var dialog  = $(data);
		dialog.find(".modal-title").html("增加字典");
		dialog.find(".modal-dialog").css('width','400');
		var str = '';
		str+=' <div class="row">  ';
		str+=' <div class="col-sm-3" style="line-height: 40px;">  ';
		str+=' <label>字典编码：</label>';
		str+=' </div>';
		str+=' <div class="col-sm-9">  ';
		str+=' <input type="text" id="dicCode" class="form-control" />';
		str+=' </div>';
		str+=' </div>';
		str+=' <div class="row">  ';
		str+=' <div class="col-sm-3" style="line-height: 40px;">  ';
		str+=' <label>字典描述：</label>';
		str+=' </div>';
		str+=' <div class="col-sm-9">  ';
		str+=' <input type="text" id="dicDesc" class="form-control"  />';
		str+=' </div>';
		str+=' </div>';
		dialog.find(".modal-body").html(str);
		dialog.find('#save').on('click', function(){
			var dictionary={
				dicCode: dialog.find("#dicCode").val(),
				dicDesc: dialog.find("#dicDesc").val()
			};
			if(!dictionary.dicCode || dictionary.dicCode==""){
				drgUI.warning("字典代码不能为空!") ;
				return ;
			}
			$.post(contextPath + "/dictionary/saveDictionary.dhc", {param: JSON.stringify(dictionary)}).done(function(data){
				if(data=="0"){
					drgUI.error("该字典代码已存在，请重新输入！") ;
				}else if(data="2"){
					drgUI.success("插入成功！") ;
					dialog.trigger('complete');
				}else{
					var errorLog = "字典("+dicCode+")报错";
					drgUI.error(errorLog) ;
				}
			})
		}).end().modal({
			keyboard : false
		}).on({
			'hidden.bs.modal' : function() {
				dialog.remove();
			},
			'complete' : function() {
				dialog.modal('hide');
				loadDictionaryDataSettings();
            }
		});
	});
	
}
/**
 * 修改字典
 * @param {} id
 */
function mergeDictionary(dicCode){
	$.post(contextPath+"/pages/common/top-dialog-buttons.jsp").done(function(data){
		var dialog  = $(data);
		dialog.find(".modal-title").html("修改字典");
		dialog.find(".modal-dialog").css('width','400');
		$.post(contextPath + "/dictionary/findDictionaryByCode.dhc", {dicCode: dicCode}).done(function(data){
			var dictionary;
			var data = data.data;
			if(data.length>0){
				dictionary = data[0]; // 只显示查询到的第一个
			}
			var str = '';
			str+=' <div class="row">  ';
			str+=' <div class="col-sm-3" style="line-height: 40px;">  ';
			str+=' <label>字典编码：</label>';
			str+=' </div>';
			str+=' <div class="col-sm-9">  ';
			str+=' <input type="text" id="dicCode" class="form-control" readonly="readonly" value="'+dictionary.DIC_CODE+'" />';
			str+=' </div>';
			str+=' </div>';
			str+=' <div class="row">  ';
			str+=' <div class="col-sm-3" style="line-height: 40px;">  ';
			str+=' <label>字典描述：</label>';
			str+=' </div>';
			str+=' <div class="col-sm-9">  ';
			str+=' <input type="text" id="dicDesc" class="form-control" value="'+dictionary.DIC_DESC+'" />';
			str+=' </div>';
			str+=' </div>';
			dialog.find(".modal-body").html(str);
		})
		dialog.find('#save').on('click', function(){
			dialog.find('#save').attr("disabled", "");  // disabled 元素数据无法获取
			var dictionary={
				dicCode: dialog.find("#dicCode").val(),
				dicDesc: dialog.find("#dicDesc").val()
			};
			if(!dictionary.dicCode || dictionary.dicCode==""){
				drgUI.warning("字典代码不能为空!") ;
				return ;
			}
				$.post(contextPath + "/dictionary/saveDictionary.dhc", {param: JSON.stringify(dictionary)}).done(function(data){
					if(data.success){
						drgUI.success("更新成功！") ;
						dialog.trigger('complete');
					}else{
						var errorLog = "字典("+dictionary.dicCode+")报错";
						drgUI.error(errorLog) ;
					}
				})
		}).end().modal({               // end():结束当前链条中的最近的筛选操作，并将匹配元素集还原为之前的状态。 modal():调用模式窗口
			keyboard : false
		}).on({
			'hidden.bs.modal' : function() {
				dialog.remove();
			},
			'complete' : function() {
				dialog.modal('hide');
				loadDictionaryDataSettings();
            }
		});
	});
}

function delDictionaryData(id){
	drgUI.confirm({
		content : '确定要删除字典吗?删除后,关联数据也将会删除',
		callSure : function() {
			$.post(contextPath + "/dictionary/delDictionary.dhc",{"dicCode":id}).done(function(data){
				if(!data.success){
					drgUI.error("删除失败,日志："+data.errorMessage) ;
				}else{
					drgUI.success("删除成功") ;
					loadDictionaryDataSettings();
				}
			});
		}
	});
}